package com.duanjw.algorithms;

/**
 * 二分查找
 * @author duanjw
 */
public class BinarySearch {
    public int rank(int key, int[] array) {
        int lo = 0;
        int hi = array.length - 1;
        // 执行次数
        int count = 0;
        while (lo <= hi) {
            count ++;
            int mid = lo + (hi - lo) / 2;
            if(key < array[mid]) {
                hi = mid - 1;
            } else if(key > array[mid]){
                lo = mid + 1;
            } else {
                System.out.println("使用二分法找到元素共执行次数：" + count);
                return array[mid];
            }
        }
        return -1;
    }
}
